package com.writing.controller;

import com.writing.common.Result;
import com.writing.service.VideoGenerationService;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import java.util.Map;

/**
 * 视频生成控制器
 */
@RestController
@RequestMapping("/videos")
@RequiredArgsConstructor
public class VideoGenerationController {

    private final VideoGenerationService videoGenerationService;

    /**
     * 生成视频
     */
    @PostMapping
    public Result<VideoTaskResponse> generateVideo(
            @RequestParam("prompt") @NotBlank(message = "提示词不能为空") String prompt,
            @RequestParam(value = "model", required = false, defaultValue = "sora-2") String model,
            @RequestParam(value = "seconds", required = false) String seconds,
            @RequestParam(value = "size", required = false, defaultValue = "720x1280") String size,
            @RequestParam(value = "input_reference", required = false) MultipartFile inputReference,
            HttpServletRequest httpRequest) {
        Long userId = (Long) httpRequest.getAttribute("userId");
        if (userId == null) {
            return Result.unauthorized("用户未登录");
        }

        try {
            VideoGenerationRequest request = new VideoGenerationRequest();
            request.setPrompt(prompt);
            request.setModel(model);
            request.setSeconds(seconds);
            request.setSize(size);
            request.setInputReference(inputReference);
            
            VideoTaskResponse response = videoGenerationService.generateVideo(request, userId);
            return Result.success("视频生成任务已创建", response);
        } catch (Exception e) {
            return Result.error("视频生成失败: " + e.getMessage());
        }
    }

    /**
     * 查询视频任务状态
     */
    @GetMapping("/{videoId}")
    public Result<VideoTaskResponse> getVideoTask(@PathVariable String videoId,
                                                  HttpServletRequest httpRequest) {
        Long userId = (Long) httpRequest.getAttribute("userId");
        if (userId == null) {
            return Result.unauthorized("用户未登录");
        }

        try {
            VideoTaskResponse response = videoGenerationService.getVideoTask(videoId, userId);
            return Result.success(response);
        } catch (Exception e) {
            return Result.error("查询视频任务失败: " + e.getMessage());
        }
    }

    /**
     * 获取视频内容（下载视频）
     */
    @GetMapping("/{videoId}/content")
    public ResponseEntity<byte[]> getVideoContent(@PathVariable String videoId,
                                                  @RequestParam(value = "variant", required = false) String variant,
                                                  HttpServletRequest httpRequest) {
        Long userId = (Long) httpRequest.getAttribute("userId");
        if (userId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }

        try {
            Map<String, Object> result = videoGenerationService.getVideoContent(videoId, variant, userId);
            byte[] videoData = (byte[]) result.get("data");
            String contentType = (String) result.get("contentType");
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType(contentType != null ? contentType : "video/mp4"));
            headers.setContentLength((Long) result.get("contentLength"));
            headers.setContentDispositionFormData("attachment", "video-" + videoId + ".mp4");
            
            return new ResponseEntity<>(videoData, headers, HttpStatus.OK);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 视频生成请求DTO
     */
    @Data
    public static class VideoGenerationRequest {
        private String prompt;
        private String model;
        private String seconds;
        private String size;
        private MultipartFile inputReference;
    }

    /**
     * 视频任务响应DTO
     */
    @Data
    public static class VideoTaskResponse {
        private String id;
        private String object;
        private String model;
        private String status;
        private Integer progress;
        private Long createdAt;
        private Long completedAt;
        private Long expiresAt;
        private String size;
        private String seconds;
        private String quality;
        private String remixedFromVideoId;
        private Object error;
        private String url;
    }
}

